package com.zh.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.vo.Result;
import com.zh.modules.app.entity.OptionsDO;
import com.zh.modules.app.entity.vo.OptionVO;
import com.zh.modules.app.repository.OptionsRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/app/option")
@Api(tags = "选项")
@Slf4j
public class OptionController {

    @Autowired
    private OptionsRepository optionRepository;

    @GetMapping("/queryByCode")
    @ApiOperation("列表查询")
    public Result<List<OptionVO>> queryByCode(String bizCode) {
        LambdaQueryWrapper<OptionsDO> queryWrapper = new LambdaQueryWrapper<OptionsDO>().
                eq(OptionsDO::getBizCode, bizCode).orderByDesc(OptionsDO::getDisplayOrder).orderByAsc(OptionsDO::getId);
        List<OptionsDO> list = optionRepository.list(queryWrapper);
        List<OptionVO> result = buildTree(list, null);
        return Result.succeed(result);
    }

    private List<OptionVO> buildTree(List<OptionsDO> list, Integer parentId) {
        List<OptionVO> tree = new ArrayList<>();
        for (OptionsDO option : list) {
            if (Objects.equals(option.getParentId(), parentId)) {
                OptionVO vo = new OptionVO();
                vo.setId(option.getId());
                vo.setParentId(option.getParentId());
                vo.setValue(option.getValue());
                vo.setLabel(option.getLabel());
                vo.setBizCode(option.getBizCode());
                vo.setChildren(buildTree(list, option.getId()));
                tree.add(vo);
            }
        }
        return tree;
    }
}
